<template>
  <div class="login-containe">
    <video
      class="video"
      muted="muted"
      src="../../assets/video/video.mp4"
      loop="loop"
      preload="auto"
      autoplay="true"
    ></video>
    <!-- <img src="../../assets/img/preview.jpg" alt="" class="img"> -->
    <!-- 常规登入 -->
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <h1 class="title">管理系统</h1>
      <i
        @click="isErweiLogin = !isErweiLogin"
        :class="[
          'jiaobiao',
          'iconfont',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>

      <div class="common-login" v-if="!isErweiLogin">
        <el-form-item label="用户名" prop="UserName">
          <el-input type="text" v-model="ruleForm.UserName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="Pass">
          <el-input type="password" v-model="ruleForm.Pass" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="Captcha" class="captcha">
          <el-input
            v-model="ruleForm.Captcha"
            @keydown.native.enter="submitForm('ruleForm')"
            ref="captcha"
          ></el-input>
          <span @click="updateCaptcha" class="captcha-svg" v-html="captchaSvg"> </span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
      </div>
      <!-- 切换二维码登入 -->
      <div class="erwei" v-else>
        <div class="img">
          <img :src="qrDataUrl" width="200px" alt="" />
          <i class="mask" style="qrStyle" v-show="isScanCodeSuccess" @click="getQrcode">
          </i>
        </div>
        <p class="hint">请使用手机微信扫码登录</p>
      </div>
      <!-- 切换手机验证码登录 -->
      <el-form-item>
        <div class="sms">
          <!-- <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-iphone"></use>
          </svg> -->
          <a
            href="javascript:;"
            @click="
              sms = true;
              isErweiLogin = true;
              title = '短信登入';
            "
            style="color: #fff; font-size: 16px"
            >切换短信登入</a
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入api中的方法
import * as api from "../../api/index";
import { mapMutations } from "vuex";
//引入socket.io
//引入生成二维码的插件qrcode
import io from "socket.io-client";
import qrcode from "qrcode";
//引入扫码成功和失效的图片
import codeSuccessImg from "../../assets/img/scancode.png";
import codeInvalidImg from "../../assets/img/invalidQr.png";
var valideteCaptcha = (rule, value, callback) => {
  //callback只要传参了表示表单验证不通过，不传参表示表单验证通过
  //value就是在input中的输入值
  //rule就是验证对象
  if (value.length !== 5) {
    callback("验证码必须是5位");
  } else {
    callback();
  }
};

var validateUserName = (rule, value, callback) => {
  var reg = /^\w{3,12}$/;
  if (reg.test(value)) {
    //验证通过
    callback();
  } else {
    callback("用户名必须是3-12位的数字、字母、下划线");
  }
};

var validatePass = (rule, value, callback) => {
  if (value.length < 3) {
    //验证通过
    callback("密码长度不能少于3位");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      isErweiLogin: false, //是否二维码登入
      smsCode: "", //短信验证码
      phoneNumber: "", //手机号
      sms: false, //
      captchaSvg: "", //验证码svg
      ruleForm: {
        //登录的数据
        UserName: "",
        Pass: "",
        Captcha: "",
      },
      rules: {
        //表单验证规则
        UserName: [{ validator: validateUserName, trigger: "blur" }],
        Pass: [{ validator: validatePass, trigger: "blur" }],
        Captcha: [{ validator: valideteCaptcha, trigger: "blur" }],
      },
      qrDataUrl: "", //二维码base64的扫码地址
      isScanCodeSuccess: "", //是否扫码成功
      qrStyle: {
        backgroundImage: `url(${codeSuccessImg})`,
      },
    };
  },
  mounted() {
    // 获取调用验证码的方法
    // console.log(process.env.VUE_APP_BASE_URL);
    this.updateCaptcha();
  },
  methods: {
    phone() {},
    //封装一个获取二维码地址的方法
    getQrcode() {
      //关掉Qrcode的遮罩层
      this.isScanCodeSuccess = false;
      //让遮罩的样式初始化
      this.qrStyle.backgroundImage = `url(${codeSuccessImg})`;
      //从本地取出Qrcode
      let sid = localStorage.getItem("qf-sid");
      if (!sid) {
        this.$message.error("没有sid");
        return;
      }
      api.getQrcodeUrlApi(sid).then((res) => {
        let qrUrl = res.data.scanCodeUrl;
        //3.通过qrcode将二维码地址生成二维码
        qrcode.toDataURL(qrUrl, (err, dataUrl) => {
          // console.log(dataUrl);
          this.qrDataUrl = dataUrl;
        });
      });
    },
    ...mapMutations(["SET_USER_INFO"]),
    //封装一个专门获取验证码的方法
    updateCaptcha() {
      api.getCaptchaApi().then((res) => {
        // console.log(res.data);
        this.captchaSvg = res.data.img;
      });
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        //所有的表单校验通过之后valid的值是true

        //不然就是false

        //1.先校验本地的表单是否通过
        //2.校验验证码是否正确
        //3.校验用户名密码是否正确
        if (valid) {
          //表单校验通过了
          //打开Loading动画
          const loading = this.$loading({
            lock: true,
            text: "正在登录...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //校验验证码
          api.verifyCaptcha(this.ruleForm.Captcha.toLowerCase()).then((res) => {
            // console.log(res);
            if (res.data.state) {
              //验证码通过
              //继续校验用户名和用户密码
              api.loginApi(this.ruleForm.UserName, this.ruleForm.Pass).then((res) => {
                // console.log(res.data);
                if (res.data.state) {
                  loading.close(); //关闭加载动画
                  this.$message.success({
                    message: "登录成功",
                    type: "success",
                    duration: 1000,
                  });
                  // console.log(res);
                  //登入成功
                  //1.将token储存到本地
                  localStorage.setItem("qf-token", res.data.token);
                  //2.将userInfo存到本地
                  localStorage.setItem("qf-userInfo", JSON.stringify(res.data.userInfo));
                  //按钮权限
                  localStorage.setItem(
                    "permissionButtons",
                    JSON.stringify(res.data.permission.buttons)
                  );
                  //将用户信息添加到vuex
                  this.SET_USER_INFO(res.data.userInfo);
                  //3.跳转到主页
                  this.$router.push("/");
                } else {
                  //登入失败，用户名或密码错误
                  loading.close(); //关闭加载动画
                  this.$message.error("账号或者密码错误");
                }
              });
            } else {
              // console.log('验证码错误');
              loading.close();
              this.$message.error("验证码错误");
              //清空验证码输入框的内容
              this.ruleForm.Captcha = "";
              //让输入框获得焦点
              this.$refs.captcha.focus();
              //验证码错误，刷新验证码
              this.updateCaptcha();
            }
          });
        } else {
          //表单校验不通过
          // console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    //监听切换二维码登录的字段
    isErweiLogin(newVal, oldVal) {
      if (newVal) {
        //已经切换成了二维码登录
        //1.通过socket.io和服务器建立连接
        let socket = io("wss://chst.vip");
        //2.监听socket连接成功事件，发送请求，请求"/users/getScancode"获取二维码地址
        socket.on("connectSuccess", (data) => {
          // console.log(data);
          //将sid存到本地
          let { sid } = data;
          localStorage.setItem("qf-sid", sid);
          //3.获取二维码地址，并且生成二维码图片
          this.getQrcode();
        });

        //4.用户扫描二维码
        //5.监听socket事件 scancodeSuccess(这个事件不是socket.io定义的，是前后端约定的),获取到的wechatCode
        socket.on("scancodeSuccess", (data) => {
          // console.log(data);
          // console.log("扫码成功");
          if (data.state) {
            //扫码成功
            //显示遮罩
            this.isScanCodeSuccess = true;
            api.wechatLoginApi(data.wechatCode).then((res) => {
              if (res.data.state) {
                // console.log(res);
                //将用户信息的token存起来
                //登入成功
                //1.将token储存到本地
                localStorage.setItem("qf-token", res.data.token);
                //2.将userInfo存到本地
                localStorage.setItem("qf-userInfo", JSON.stringify(res.data.userInfo));
                //3.将用户信息保存到vuex
                this.SET_USER_INFO(res.data.userInfo);
                //按钮权限
                localStorage.setItem(
                  "permissionButtons",
                  JSON.stringify(res.data.permission.buttons)
                );
                //4.跳转到首页
                this.$router.push("/");
              } else {
                //登录失败
                loading.close(); //关闭加载动画
                this.$message.error("微信登录失败");
              }
            });
          } else {
            //提示扫码失败
            this.$message.error("扫码失败");
          }
        });
        //6.请求users/wechatLogin,传递wechatCode

        //7.判断成功和失败

        socket.on("invalidCode", (data) => {
          console.log(data);
          this.qrStyle.backgroundImage = `url(${codeInvalidImg})`; //显示二维码失效的标志
          this.qrStyle.cursor = "pointer"; //让图标变得可以点击
          this.isScanCodeSuccess = true; //二维码失效显示遮罩
        });
      } else {
        //切换成普通登录
        //二维码遮罩关闭
        this.isScanCodeSuccess = false;
      }
    },
  },
};
</script>

<style scoped lang="less">
.login-containe {
  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    opacity: 0.7;
  }
  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  //二维码样式
  .erwei .img {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
    img {
      position: absolute;
      left: 50%;
    }
    // .hint{
    //   display: block;
    //   margin-block-start:1em ;
    //   margin-block-end: 1em;
    //   margin-inline-start:0px;
    //   margin-inline-end: 0px;
    //   text-align: center!important;
    //   color: #fff!important;
    // }
    .mask {
      width: 100%;
      height: 100%;
      opacity: 0.8;
      background-color: #fff;
      position: absolute;
      left: 50%;
      // background-image: url("../../assets/img/scancode.png");
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: center;
      cursor: pointer;
    }
  }
  // .img{
  //   position:fixed;
  //   left: 0;
  //   top: 0;
  //   right: 0;
  //   bottom: 0;
  // }
  .el-form {
    position: fixed;
    right: 10%;
    top: 23%;
    padding: 100px 0 50px 0;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    /deep/.el-input__inner {
      width: 250px;
      padding-bottom: 15px;
    }
    .el-form-item__content {
      position: relative;
      .captcha-svg {
        background: #fff;
        display: inline-block;
        height: 45px;
        width: 150px;
        text-align: center;
        cursor: pointer;
        border: 0;
        border-radius: 0 5px 5px 0;
        position: absolute;
        top: 5px;
        left: 100px;
      }
    }
    .captcha /deep/ .el-input__inner {
      width: 100px;
      height: 45px;
      border-radius: 5px 0 0 5px;
      border: 0;
      font-size: 18px;
    }
    .el-button--primary {
      background: linear-gradient(90deg, #1596fb, #002dff);
      width: 250px;
    }
    /deep/ .el-form-item__label {
      color: #fff;
    }
  }
  .common-login {
    padding: 0 50px 0 0;
  }
  .title {
    margin: 0 0 60px;
    text-align: center;
    color: #fff;
  }
}
.sms {
  margin-left: -15px !important;
  width: 250px !important;
}

/deep/ .phone {
  width: 150px !important;
  margin-left: 150px;
  color: #fff;
  cursor: pointer;
}
.smsContainer {
  padding-right: 20px !important;
  width: 89%;

  /deep/ .el-form-item__label {
    // margin-left: 80px !important
    padding: 0 !important;
    padding-right: 10px !important;
  }

  /deep/ .phone {
    width: 140px !important;
  }

  /deep/ .captcha-svg {
    width: 115px !important;
  }

  /deep/ .el-form-item__content {
    margin: 0;
  }
}
</style>
